package com.cxf.windex.rest;

import com.cxf.windex.base.msg.ObjectRestResponse;
import com.cxf.windex.base.msg.TableResultResponse;
import com.cxf.windex.base.rest.BaseRestController;
import com.cxf.windex.base.util.IdUtil;
import com.cxf.windex.biz.JsContentsBiz;
import com.cxf.windex.entity.JsContents;
import com.github.pagehelper.PageHelper;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author chenxf
 * @date 3/8/2018
 * @description
 */
@Api(tags = {"小程序 - 资讯接口"})
@Controller
@RequestMapping("/user/content")
public class ContentController extends
        BaseRestController<JsContentsBiz, JsContents> {


  public static Pattern p = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");

  /**
   * 文件存放 路径
   */
  @Value("${upload.path}")
  private String uploadPath;

  /**
   * 文件访问路径
   */
  @Value("${upload.url}")
  private String uploadUrl;

  /**
   * 文件访问域名
   */
  @Value("${upload.uri}")
  private String uploadUri;


  @ApiOperation(value = "新增/编辑", notes = "新增编辑")
  @RequestMapping(value = "/edit", method = RequestMethod.GET)
  @ResponseBody
  public ObjectRestResponse edit(JsContents entity) {
    if (StringUtils.isBlank(entity.getId())) {
      return new ObjectRestResponse().rel(true).msg("文章ID不能为空");
    }
    entity = baseBiz.selectById(entity.getId());
    return new ObjectRestResponse().rel(true).msg("查询成功").result(entity);
  }

  @Cacheable(value="articleList")
  @ApiOperation(value = "查询文章列表", notes = "查询文章列表")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "limit", value = "记录数", required = false, paramType = "query", dataType = "int"),
      @ApiImplicitParam(name = "offset", value = "页码", required = false, paramType = "query", dataType = "int"),
      @ApiImplicitParam(name = "orderStr", value = "排序 desc", required = false, paramType = "query", dataType = "String"),
      @ApiImplicitParam(name = "title", value = "标题", required = false, paramType = "query", dataType = "String"),
      @ApiImplicitParam(name = "type", value = "类型", required = false, paramType = "query", dataType = "String")
  })
  @RequestMapping(value = "/list", method = RequestMethod.GET)
  @ResponseBody
  public TableResultResponse<JsContents> list(
          @RequestParam(defaultValue = "10") int limit, @RequestParam(defaultValue = "1") int offset,
          @RequestParam(defaultValue = "desc") String orderStr, String title, String type) {
    Example example = new Example(JsContents.class);
    Criteria criteria = example.createCriteria();
    if (StringUtils.isNotBlank(title)) {
      criteria.andLike("title", "%" + title + "%");
    }
    if (StringUtils.isNotBlank(type)) {
      criteria.andLike("type", "%" + type + "%");
    }

    int count = baseBiz.selectCountByExample(example);
    PageHelper.startPage(offset, limit);
    PageHelper.orderBy("crt_time " + orderStr);

    return new TableResultResponse<JsContents>(count, offset, limit,
        baseBiz.selectByExample(example));

  }

  @CacheEvict(value="articleList",allEntries=true)
  @ApiOperation(value = "保存", notes = "保存")
  @RequestMapping(value = "/edit", method = RequestMethod.POST)
  @ResponseBody
  public ObjectRestResponse save(@RequestBody JsContents entity) {
    String type = "edit";
    if (StringUtils.isBlank(entity.getId())) {
      type = "insert";
      entity.setId(new IdUtil(4, 1).nextId() + "");
    }
    if (StringUtils.isNotBlank(entity.getContent()) &&
        entity.getContent().contains("img")) {
      entity.setImage(getImg(entity.getContent()));
    }
    String userId = this.getCurrentUserId();
    entity.setCrtUser(userId);

    if (type.equals("insert")) {
      baseBiz.insertSelective(entity);
    } else {
      baseBiz.updateSelectiveById(entity);
    }
    return new ObjectRestResponse().rel(true).msg("保存成功");
  }

  @ApiOperation(value = "上传图片", notes = "上传图片")
  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  @ResponseBody
  public Map upload(@RequestParam("file") MultipartFile file) {
    Map resultMap = new HashMap();
    if (file != null) {
      Map<String, String> savePcMap = saveFile(request, file, "article", uploadPath, uploadUrl,uploadUri);
      if (savePcMap != null) {
        if (savePcMap.get("code").equals("0")) {
          Map fileMap = new HashMap();
          fileMap.put("src", savePcMap.get("saveUrl"));
          resultMap.putAll(savePcMap);
          resultMap.put("data", fileMap);
          return resultMap;
        } else {
          return savePcMap;
        }
      }
    }
    return resultMap;
  }

  public String getImg(String content) {
    Matcher m = p.matcher(content);
    if (m.find()) {
      return m.group(1);
    }
    return "";
  }
}
